#!/bin/bash
# 必须以root用户运行，以下进行检测
echo -e "\e[38;5;206m---------1.检测用户权限------------\e[0m"

if [ $(id -u) -ne 0 ]; then
	# echo "Must be root to run this script."
	echo "必须以 root 用户执行本脚本！"
	echo "如果未初始化root，请执行：sudo passwd root"
	echo "如果已初始化，请使用 su 切换到root账号下"
	exit $E_NOTROOT
fi
echo "正在安装系统依赖包......"
apt-get update -y
apt-get install vim openssh-server git curl -y
echo "系统依赖包完成......"
echo "-------------------"
echo "-------------------"
echo -e "\e[38;5;206m---------2.变量输入------------\e[0m"
random_string=$(cat /dev/urandom | tr -dc 'A-Z' | fold -w 16 | head -n 1)
while true; do
    read -p "请输入工厂中文名称: " userInput

    if [ -z "$userInput" ]; then
        echo "输入不能为空，请重新输入。"
    else
        break
    fi
done
while true; do
    read -p "请输入工厂服务端内网ip地址(192.168.88.251): " inputServerIP

    if [ -z "$inputServerIP" ]; then
        ServerIP='192.168.88.251'
        echo "内网ip地址默认：$ServerIP"
        break
    else
        ServerIP="$inputServerIP"
        echo "您输入的内网ip地址：$ServerIP"
        break
    fi
done
if [ ! -f ~/.ssh/id_rsa.pub ]; then
    echo "秘钥不存在，正在创建中..."
    ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
fi
# 检查秘钥是否存在
if [ ! -f ~/.ssh/id_rsa.pub ]; then
	exit "创建秘钥失败!"
fi
cat ~/.ssh/id_rsa.pub

ssh_key=$(cat ~/.ssh/id_rsa.pub)
echo "$random_string" > /data/unique_id.txt
echo "$ServerIP" > /data/server_ip.txt
echo "$userInput" > /data/user_input.txt

curl --location --request POST 'http://monitor.8kfm.com/api/api/service_manage/service_info/init/' \
--header 'Content-Type: application/json' \
--data-raw "{
    \"name\": \"$userInput\",
    \"unique_id\": \"$random_string\",
    \"tenant_id\": 100001,
    \"ssh_key\": \"$ssh_key\",
    \"service_ip\": \"$ServerIP\"
}"
echo -e "\e[38;5;226m 请管理进行审核"
read -p " 审核通过后，按回车继续......"
while true; do
    if [ ! -d "/data/" ]; then
        read -p "请挂载数据盘，挂载后按回车继续..."
    else
    		echo -e "\e[38;5;206m---------数据盘检测挂载正常------------\e[0m"
        break
    fi
done
echo -e "\e[38;5;206m---------3.拉取代码------------\e[0m"
# 指定code的文件夹名称
folder_name="/data/kfm-code"
# 检查文件夹是否存在
if [ ! -d "$folder_name" ]; then
    # 如果文件夹不存在，则创建它
    mkdir -p "$folder_name"
fi
apt install git
cd $folder_name
git clone git@codeup.aliyun.com:kfm/code/packaging-coding.git
echo -e "\e[38;5;206m---------4.安装docker与docker-compose------------\e[0m"
sudo apt-get install docker.io -y
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://docker.docker.kungfumars.com", "https://al2jc4wb.mirror.aliyuncs.com"],
  "data-root": "/data/docker"
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo rm /usr/local/bin/docker-compose
sudo curl -L "https://cdn.kungfumars.com/packaging-coding/deploy/docker-compose-Linux-x86_64"  -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
echo -e "\e[38;5;226m---------拉取拉取成功，执行代码中部署脚本------------\e[0m"
bash /data/kfm-code/packaging-coding/backend/deploy.sh